<template>
  <div class="snack">
    <input
      type="text"
      @keyup="changeMoveWay"
      ref="inputDom"
      @blur="focus"
      style="opacity: 0"
    />
    <div class="startGame">
      <score-pane :score="snackScore"></score-pane>
      <button class="snack-startgame" @click="initMove" :disabled="ifStart">
        开始游戏
      </button>
      <button class="snack-startgame" @click="goBack" :disabled="ifStart">返回</button>
    </div>
    <div class="out">
      <div
        class="in"
        :style="{
          backgroundColor: snackBody.includes(index)
            ? '#000'
            : foodBody === index
            ? 'red'
            : 'rgba(255,255,255,0.6)',
        }"
        v-for="(item, index) in arr"
        :key="index"
      ></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import scorePane from "./scorePane.vue";
import { computed, ref, onMounted, defineEmits, onBeforeUnmount } from "vue";
const message = ref("Hello Vue!");
const arr = ref<Array<any>>([]);
const snackArr = ref([0]);
const showDom = ref(true);
const moveWay = ref("right");
const snackSonBody = ref(["1,1"]);
const ifStart = ref<boolean>(false);
const foodDot = ref("");
const timer = ref<number | null>(null);
const inputDom = ref<HTMLInputElement | null>(null);
onBeforeUnmount(() => {
  timer.value && clearInterval(timer.value);
});
onMounted(() => {
  const a: Array<any> = [];
  a.length = 200;
  a.fill("");
  arr.value = a;
  randomShowFood();
  inputDom.value!.focus();
});
const emit = defineEmits(["goBack"]);
const goBack = () => {
  emit("goBack");
};
const snackBody = computed(() => {
  return snackSonBody.value.map((item) => {
    const itemArr = item.split(",");
    const rownum: number = parseInt(itemArr[0]) - 1;
    const columnnum: number = parseInt(itemArr[1]) - 1;
    const currentnum = columnnum * 20 + rownum * 1;
    return currentnum;
  });
});
const foodBody = computed(() => {
  const itemArr: Array<string> = foodDot.value.split(",");
  const rownum: number = parseInt(itemArr[0]) - 1;
  const columnnum: number = parseInt(itemArr[1]) - 1;
  const currentnum = columnnum * 20 + rownum * 1;
  return currentnum;
});
const focus = () => {
  inputDom.value && inputDom.value.focus();
};
const clear = () => {
  snackSonBody.value = ["1,1"];
  moveWay.value = "right";
};
const initMove = () => {
  ifStart.value = true;
  timer.value = setInterval(() => {
    move();
  }, 200);
};
const randomShowFood = () => {
  const row = Math.ceil(Math.random() * 20);
  const column = Math.ceil(Math.random() * 10);
  if (snackSonBody.value.find((item) => item + "" === `${row},${column}`)) {
    randomShowFood();
    return;
  }
  foodDot.value = `${row},${column}`;
};
const changeMoveWay = (e: KeyboardEvent) => {
  switch (e.keyCode) {
    case 39:
      moveWay.value !== "right" && moveWay.value !== "left" && (moveWay.value = "right");
      break;
    case 40:
      moveWay.value !== "down" && moveWay.value !== "up" && (moveWay.value = "down");
      break;
    case 37:
      moveWay.value !== "left" && moveWay.value !== "right" && (moveWay.value = "left");
      break;
    case 38:
      moveWay.value !== "down" && moveWay.value !== "up" && (moveWay.value = "up");
      break;
    default:
      return;
  }
};
const fail = () => {
  clear();
  alert("失败");
  timer.value && clearInterval(timer.value);
  ifStart.value = false;
};
const move = () => {
  const first = snackSonBody.value[snackSonBody.value.length - 1];

  const firstBody: Array<string> = first.split(",");
  let moveDot = "";
  const oneBody = parseInt(firstBody[1]);
  const zeroBody = parseInt(firstBody[0]);
  switch (moveWay.value) {
    case "down":
      moveDot = `${zeroBody},${oneBody + 1}`;
      break;
    case "up":
      moveDot = `${zeroBody},${oneBody - 1}`;
      break;
    case "left":
      moveDot = `${zeroBody - 1},${oneBody}`;
      break;
    case "right":
      moveDot = `${zeroBody + 1},${oneBody}`;
      break;
  }

  const row = parseInt(moveDot.split(",")[0]);
  const column = parseInt(moveDot.split(",")[1]);
  if (row < 1 || row > 20 || column < 1 || column > 10) {
    fail();
    return;
  }
  if (snackSonBody.value.includes(moveDot)) {
    fail();
    return;
  }
  snackSonBody.value.push(moveDot);
  if (moveDot !== foodDot.value) {
    snackSonBody.value.shift();
  } else {
    freshScore();
    randomShowFood();
  }
};
const snackScore = ref<number>(0);
const freshScore = () => {
  snackScore.value++;
  const bestScore = localStorage.getItem("snackBestScore") || 0;
  snackScore.value > bestScore &&
    localStorage.setItem("snackBestScore", snackScore.value + "");
};
</script>

<style scoped lang="scss">
.in {
  width: 50px;
  /* height: 48px; */
  background-color: #000;
  margin: 0;
  font-size: 0;
  /* border: 1px solid #000; */
  color: #fff;
}
.out {
  display: flex;
  flex-wrap: wrap;
  width: 1000px;
  height: 500px;
  overflow: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
#app {
  position: relative;
}
.snack {
  position: relative;
  width: 100%;
  height: calc(100vh - 50px);
}
.snack .snack-startgame {
  text-align: center;
}
.snack div {
  /* width: 50px;
  height: 50px; */
}
.startGame {
  text-align: center;
  position: relative;
}
.startGame .snack-startgame {
  margin: 30px 16px 0;
  width: 75px;
  height: 35px;
  background-color: #3478ec99;
  border: none;
  font-size: 13px;
  flex-wrap: bold;
  color: #000;
  border-radius: 5px;
  &:hover {
    background: #3478ec88;
  }
}
</style>
